package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.StampedLock;

@Service
@Slf4j
public class StampedLockCounterService {

    private final StampedLock stampedLock = new StampedLock();
    private int counter = 0;

    // 多线程计数器递增示例
    public void incrementCounter() {
        long stamp = stampedLock.writeLock();  // 获取写锁
        try {
            counter++;  // 增加计数器
            log.info("计数器增加后值为: {}", counter);
        } finally {
            stampedLock.unlockWrite(stamp);  // 释放写锁
        }
    }

    // 读取计数器值
    public int getCounter() {
        long stamp = stampedLock.readLock();  // 获取读锁
        try {
            log.info("当前计数器值为: {}", counter);
            return counter;  // 返回计数器值
        } finally {
            stampedLock.unlockRead(stamp);  // 释放读锁
        }
    }
}
